import { API, request } from "./request";
import store from "@/store";
import { fetchUserInfo } from "~@/common/user";

export const register = (getPhoneNumberCode, callback) => {
  if (!getPhoneNumberCode || getPhoneNumberCode === "") {
    return;
  }
  mnpLogin().then((weixin_token) => {
    request({
      path: API.LOGIN_MINIPROGRAM_LOGIN,
      params: {
        wx_login_code: weixin_token,
        phone_code: getPhoneNumberCode,
        invitation_code: store.state.to_be_invitation_code,
      },
    }).then((data) => {
      uni.setStorageSync("token", data.data.token);
      var userInfo = store.state.userInfo;
      userInfo.token = data.data.token;
      store.commit("SET_USER_INFO", userInfo);
      fetchUserInfo(callback);
    });
  });
};

export const fetchUserMnpToken = (callback) => {
  mnpLogin().then((weixin_token) => {
    fetchToken(weixin_token).then((data) => {
      if (data.isSuccess) {
        uni.setStorageSync("token", data.data.token);
        var userInfo = store.state.userInfo;
        userInfo.token = data.data.token;
        store.commit("SET_USER_INFO", userInfo);
        fetchUserInfo(callback);
      }
    });
  });
};

export const fetchUserInviteCode = () => {
  request({
    path: API.USER_INVITATION_CODE,
    params: {},
    method: "POST",
  }).then((data) => {
    if (data.isSuccess) {
      store.commit("SET_INVITATION_CODE", data.data.invitation_code);
    }
  });
};

function mnpLogin() {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: "weixin",
      success: (res) => {
        console.log("weixin login res", res);
        if (res.code) {
          let weixin_code = res.code;
          console.log("weixin code" + weixin_code);
          resolve(weixin_code);
        } else {
          console.log("微信登录失败");
          reject();
        }
      },
    });
  });
}

function fetchToken(weixin_code) {
  return request({
    path: API.LOGIN_MINIPROGRAM_FETCH_TOKEN,
    params: {
      wx_login_code: weixin_code,
    },
  });
}
